from django.shortcuts import render
from rest_framework import status
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
# Create your views here.
from rest_framework_jwt.settings import api_settings

from .serializers import OAuthQQUserSerializer
from .models import OAuthQQUser
from oauth.exceptions import OAuthQQAPIError
from oauth.utils import OAuthQQ
from carts.utils import merge_cart_cookie_to_redis


# 返回QQ登录页面给用户
# /oauth/qq/authorization/?next=xxx
class QQAuthURLView(APIView):
    def get(self, request):
        next = request.query_params.get('next')
        oauth = OAuthQQ(state=next)
        login_url = oauth.get_qq_login_url()
        return Response({'login_url': login_url})


# 拿到用户返回的ｃｏｄｅ请求ＱＱ的服务器
# GET /oauth/qq/user/?code=xxx
# 这个是前端在给用户登录成功之后callback.html加载的时候请求过来的
class QQAuthUserView(CreateAPIView):
    """
    QQ登录的用户  ?code=xxxx
    """
    serializer_class = OAuthQQUserSerializer

    def get(self, request):
        code = request.query_params.get('code')
        if not code:
            return Response({'message': '缺少参数'}, status=status.HTTP_400_BAD_REQUEST)
        oauth = OAuthQQ()
        try:
            # 凭借code 获取access_token
            access_token = oauth.get_access_token(code)
            # 凭借access_token 获取openid
            openid = oauth.get_openid(access_token)
        except Exception:
            return Response({'message': '访问QQ接口异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
        try:
            # 在django里面，未查询到信息会报错，到except里面，是没有查询到openid的情况
            # 查询数据库 OAuthQQUser 判断用户是否绑定过
            login_user = OAuthQQUser.objects.get(openid=openid)   # 这里要通过外键获取ｕｓｅｒ用户
            user = login_user.user
            # 如果查询到记录 证明绑定过，签发JWT token
            # 补充生成记录登录状态的token
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            user.token = token
            response = Response({
                'user_id': user.id,
                'username': user.username,
                'token': token
            })
            # 合并购物车
            response = merge_cart_cookie_to_redis(request, user, response)
            return response

        except OAuthQQUser.DoesNotExist:
            # 如果未查到，处理open_id, 构造自己的access_token,并返回
            # 使用itsdangerous模块
            access_token = oauth.generate_save_user_token(openid)
            return Response({'access_token': access_token})
        # else:
        #
        #     return Response({
        #         'user_id': user.id,
        #         'username': user.username,
        #         'token': token
        #     })

    def post(self, request, *args, **kwargs):
        response = super().post(request, *args, **kwargs)
        # 获取类视图的属性，这个在序列化器中有添加
        user = self.user
        response = merge_cart_cookie_to_redis(request, user, response)
        return response


